import { useState, useRef } from 'react'
import styled from 'styled-components'
import { Wrapper as BaseWrapper } from './FileBlob.styled'

/**
  window.showDirectoryPicker();
  dirHandle.values
  dirHandle.getFileHandle
 */
const Wrapper = styled(BaseWrapper)`
  & ul {
    list-style: circle;
  }
  & li {
    padding: .2rem;
    cursor: pointer;
  }
  & li:hover {
    color: red;
    font-weight: bolder;
  }

`
export const Demo = ()=> {
  const ref = useRef<any>(null)
  const [list, setList] = useState<any[]>([])
  const [dirHandle, setDirHandle] = useState<any>(null)
  
  const onOpenDir = async () => {
    const fsfHandle = await (window as any).showDirectoryPicker();
    if (!fsfHandle) return
    console.log(fsfHandle)
    const entries = await fsfHandle.values();
    console.log(entries)
    const items:any[] = []
    for await (const entry of entries) {
      console.log(entry.name, entry)
      if (!!entry.name) {
        items.push(`${entry.name}${(entry.kind === 'file') ? '' : ` (${entry.kind})`}`)
      }
    }
    if (!!items.length) {
      setDirHandle(fsfHandle)
      setList(items)
    }
  }
  const onClickFileName = (filename:string) => async () => {
    const fHandle = await dirHandle.getFileHandle(filename, {});
    console.log(fHandle)
    if (fHandle.kind === 'file') {
      const f = await fHandle.getFile();
      if (!f) return
      console.log(f)
      const t = await f.text();
      ref.current.value = t;
    }
  }
  const onOpenFile = async () => {
    const [fHandle] = await (window as any).showOpenFilePicker();
    console.log(fHandle)
    if (fHandle.kind === 'file') {
      const f = await fHandle.getFile();
      if (!f) return
      console.log(f)
      const t = await f.text();
      ref.current.value = t;
    }
  }
  return (
    <Wrapper>
      <h1>FileSystemHandle for folder</h1>
      <button onClick={onOpenFile}>file picker</button>
      <button onClick={onOpenDir}>folder picker</button>

      { !!list.length &&
      <ul>
      { list.map((item) => (
        <li onClick={onClickFileName(item)}>
          {item}
        </li>
      )) }
      </ul>
      }
      <textarea ref={ref}></textarea>

    </Wrapper>
  )
}
